package com.example.myprojectoffeixue;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class YouXianActivity extends Activity {
    private boolean isConnect = false;
    private OutputStream outStream;
    private OutputStream outStream1;
    private ReceiveThread receiveThread = null;
    private String strMessage = "FC000B000000000000000001000309";
    private boolean isReceive = false;
    private Socket socket = null;
    private String SSID;
    private String password;
    private String IP;
    private String port;
    AlertDialog isExit;
    String  type;
    int value;
    int time = 0;
    String jami;
    private static final String ServerIP = "192.168.121.1";
    private static final int ServerPort = 8100;
    private TextView tv_finish;
    private int preColor = Color.parseColor("#76A6EF");
    private int progressColor = Color.parseColor("#ececec");
    private int CircleColor = Color.parseColor("#ffffff");
    private int textColor = Color.parseColor("#76A6EF");
    private boolean flag = true;
    private int flag2 = 0;
    int host_netId = 0;
    int gate_netId = 0;
    private CircleProgress pv;
    WifiAdmin wifiAdmin;
    TextView dialog_set;
    MyApplication m;
    int add_time = 0;
    public int connect_time = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_you_xian);
        dialog_set = (TextView) findViewById(R.id.dialog_set);
        m = (MyApplication) getApplication();
        wifiAdmin = new WifiAdmin(this);
        wifiAdmin.openWifi();
        wifiAdmin.startScan();
        List<ScanResult> all_connectwifi= wifiAdmin.mWifiManager.getScanResults();
        if(all_connectwifi!=null){
        for (int i = 0; i < all_connectwifi.size(); i++) {
            if (all_connectwifi.get(i)!=null&&m.SSID.equals(all_connectwifi.get(i).SSID)) {
                type=all_connectwifi.get(i).capabilities;
            }
        }
        if(type.equals("[WPA2-PSK-CCMP+TKIP][ESS]")){
            Log.d("type2222",type);
            wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(m.SSID, "12345678", 3));
        }else if(type.equals("[ESS]")){
            Log.d("type0000","NoPass");
            wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(m.SSID, "", 1));
        }}else{
            wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(m.SSID, "", 1));
        }


        List<WifiConfiguration> wfg_all_connectwifi = wifiAdmin.getConfiguration();
        for (int i = 0; i < wfg_all_connectwifi.size(); i++) {
            if (("\"" + m.Host_SSid + "\"").equals(wfg_all_connectwifi.get(i).SSID)) {
                host_netId = wfg_all_connectwifi.get(i).networkId;
            }

        }

      /*
        if(gate_netId!=0){
            wifiAdmin.mWifiManager.enableNetwork(gate_netId, true);

        }else{
            wifiAdmin.disconnectWifi(wifiAdmin.getNetworkId());
            wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(m.SSID, "12345678", 3));
        }

        */

        han.sendEmptyMessageDelayed(m.time_value, 100);
        tv_finish = (TextView) findViewById(R.id.tv_finish);
        pv = (CircleProgress) findViewById(R.id.progressview1);
        pv.setTextColor(textColor);
        pv.setCircleBackgroud(CircleColor);
        pv.setPreProgress(progressColor).setProgress(preColor);
        pv.setProdressWidth(10);
        pv.setPaddingscale(0.8f);
        LinearLayout Mywangguan = (LinearLayout) findViewById(R.id.iv_mykaiguan);


        Mywangguan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buliddialog();
            }
        });
    }

    Handler han = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String msg_flag = (String) msg.obj;
            if ("fs".equals(msg_flag)) {
                dialog_set.setText("正在配置网关，请稍后...");

            } else if ("szcg".equals(msg_flag)) {
                m.time_value = value;
                dialog_set.setText("正在重启网关，请稍后...");
            } else {
                pv.setValue(msg.what);
                value = msg.what;
                if (flag) {
                    if (msg.what == 25) {
                        new Thread(connectThread).start();
                        Log.d("startconnect", "connect");
                    }
                    if (msg.what == 35) {
                        String IP = UserClass.WSServerIP;
                        String port = "9992";
                        //String port = "11342";
                        String DRR = "01";
                        String D0 = "00";
                        String D1 = "02";
                        String TP = "0001";
                        String Mac = "000000000000";
                        String ip的长度 = Integer.toHexString(IP.length());
                        if (isEven01(ip的长度.length()) == false) {
                            ip的长度 = "0" + ip的长度;
                        }
                        String ip1 = str2HexStr(IP);

                        String POST = Integer.toHexString(Integer.parseInt(port));
                        if (isEven01(POST.length()) == false) {
                            POST = "0" + POST;
                        }
                        String command = TP + Mac + DRR + D0 + D1 + ip的长度 + ip1 + POST;
                        String topsecond = null;
                        int length = 2 + 6 + 3 + IP.length() + 1 + 2;
                        topsecond = Integer.toHexString(length);
                        if (Integer.toHexString(length).length() == 1) {
                            topsecond = "000" + Integer.toHexString(length);
                        }
                        if (Integer.toHexString(length).length() == 2) {
                            topsecond = "00" + Integer.toHexString(length);
                        }
                        if (Integer.toHexString(length).length() == 3) {
                            topsecond = "0" + Integer.toHexString(length);
                        }
                        command = topsecond + command;
                        command = command.replace(" ", "");
                        byte[] data = hexStringToBytes(command);
                        byte sigle = GetXOR(data);
                        String b = bytesToHexString(new byte[]{sigle});
                        command = "FC" + command + b;
                        strMessage = command;
                        if (isConnect == true) {
                            new Thread(sendThread1).start();
                        } else {
                            flag = false;
                        }
                    } else if (msg.what == 100) {
                        if (flag2 == 1) {
                            m.time_value = 0;
                            time = 100;
                            Intent it = new Intent(YouXianActivity.this,MainActivity.class);
                            startActivity(it);
                            finish();
                            return;
                        } else if (flag2 == 4) {
                            if (connect_time == 0) {
                                tv_finish.setVisibility(View.VISIBLE);
                                tv_finish.setText("网络延迟，点击重试");
                                if ("网络延迟，点击重试".equals(tv_finish.getText().toString())) {
                                    tv_finish.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            han.sendEmptyMessageDelayed(m.time_value + 1, 500);
                                            connect_time++;

                                        }
                                    });
                                }

                            } else {
                                m.time_value = 0;
                                tv_finish.setVisibility(View.VISIBLE);
                                tv_finish.setText("网络原因，配置失败");
                                if ("网络原因，配置失败".equals(tv_finish.getText().toString())) {

                                    tv_finish.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            YouXianActivity.this.finish();
                                        }
                                    });
                                }
                            }
                        } else if (flag2 == 3) {
                            m.time_value = 0;
                            tv_finish.setVisibility(View.VISIBLE);
                            tv_finish.setText("该网关已添加");
                            if ("该网关已添加".equals(tv_finish.getText().toString())) {
                                tv_finish.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        YouXianActivity.this.finish();
                                    }
                                });
                            }
                        } else if (flag2 == 2) {
                            m.time_value = 0;
                            tv_finish.setVisibility(View.VISIBLE);
                            tv_finish.setText("网关异常，请重新配置");
                            if ("网关异常，请重新配置".equals(tv_finish.getText().toString())) {
                                tv_finish.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        YouXianActivity.this.finish();
                                    }
                                });
                            }
                        }
                    } else if (msg.what == 95 || msg.what == 80 || msg.what == 60) {
                        if (add_time == 0) {
                            addwg();
                        }

                    }
                    if (flag2 == 1) {
                        han.sendEmptyMessageDelayed(100, 500);
                    } else {
                        han.sendEmptyMessageDelayed(msg.what + 1, 500);
                    }

                }
            }
        }
    };

    Runnable connectThread = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                Log.d("connect", "开始了");
                // 初始化Scoket，连接到服务器
                socket = new Socket(ServerIP, ServerPort);
                Log.d("connect", "正在连接");
                outStream1 = socket.getOutputStream();
                isConnect = true;
                Log.d("connect", "连上了");
                // 启动接收线程
                isReceive = true;
                receiveThread = new ReceiveThread(socket);
                receiveThread.start();
                //new Thread(sendThread).start();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("UnknownHostException-->" + e.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("IOException" + e.toString());
            }
        }
    };

    // 发送消息的接口
    Runnable sendThread1 = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                outStream1.write(chatOrders(strMessage));
                Message msg = new Message();
                msg.obj = "fs";
                han.sendMessage(msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    private class ReceiveThread extends Thread {
        private InputStream inStream = null;

        ReceiveThread(Socket socket) {
            try {

                inStream = socket.getInputStream();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // ASIIC

        public void run() {
            DataInputStream dis = null;
            byte[] bytes = new byte[512];

            try {
                while (true) {
                    //读取客户端数据
                    dis = new DataInputStream(socket.getInputStream());
                    int len = dis.read(bytes);
                    if (len != -1) {
                            String bT = bytesToHexString(bytes);
                             Log.d("bt", bT);
                            String d = bT.substring(28, 30);
                            Log.d("bt2", bT);
                            m.mac_user = bT.substring(10, 22);
                            Message msg = new Message();
                            msg.obj = "szcg";
                            han.sendMessage(msg);
                            bytes = null;
                            bytes = new byte[512];

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (dis != null) {
                        dis.close();
                    }
                    if (socket != null) {
                        socket = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static byte[] mergeArray(byte[]... a) {
        // 合并完之后数组的总长度
        int index = 0;
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum = sum + a[i].length;
        }
        byte[] result = new byte[sum];
        for (int i = 0; i < a.length; i++) {
            int lengthOne = a[i].length;
            if (lengthOne == 0) {
                continue;
            }
            // 拷贝数组
            System.arraycopy(a[i], 0, result, index, lengthOne);
            index = index + lengthOne;
        }
        return result;
    }


    public static byte uniteByte(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    public static byte[] chatOrder(byte[] m) {
        if (m.length % 2 == 0) {
            byte[] bytes = new byte[m.length / 2];
            for (int i = 0, j = 0; i < m.length; i += 2, j++) {
                bytes[j] = uniteByte(m[i], m[i + 1]);
            }
            return bytes;
        }

        return null;
    }

    public static byte[] chatOrders(String c) {
        byte[] m = c.getBytes();
        return chatOrder(m);
    }

    Runnable sendThread = new Runnable() {

        @Override
        public void run() {

            byte[] sendBuffer = null;

            try {

            } catch (Exception e1) {

                e1.printStackTrace();
            }

            try {
                outStream = socket.getOutputStream();
            } catch (IOException e) {

                e.printStackTrace();
            }
            try {
                Log.i("test5", "strMessage=" + strMessage);
                outStream.write(hex2Byte(strMessage));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    private Spinner sp;


    /**
     * 16进制字符串转换成byte数组
     *
     * @return 转换后的byte数组
     * @param16进制字符串
     */
    public static byte[] hex2Byte(String hex) {
        String digital = "0123456789ABCDEF";
        char[] hex2char = hex.toCharArray();
        byte[] bytes = new byte[hex.length() / 2];
        int temp;
        for (int i = 0; i < bytes.length; i++) {
            // 其实和上面的函数是一样的 multiple 16 就是右移4位 这样就成了高4位了
            // 然后和低四位相加， 相当于 位操作"|"
            // 相加后的数字 进行 位 "&" 操作 防止负数的自动扩展. {0xff byte最大表示数}
            temp = digital.indexOf(hex2char[2 * i]) * 16;
            temp += digital.indexOf(hex2char[2 * i + 1]);
            bytes[i] = (byte) (temp & 0xff);
        }
        return bytes;
    }

    public static class handle {
        public int state;
        public String info;
        public String result;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     * @paramString str 待转换的ASCII字符串
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            //sb.append(' ');
        }
        return sb.toString().trim();
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static byte GetXOR(byte[] Cmd) {
        if (Cmd.length > 1) {
            byte check = (byte) (Cmd[0] ^ Cmd[1]);
            for (int i = 2; i < Cmd.length; i++) {
                check = (byte) (check ^ Cmd[i]);
            }
            return check;
        } else {
            return Cmd[0];
        }
    }


    public static boolean isEven01(int num) {
        if (num % 2 == 0) {
            return true;
        } else {
            return false;
        }
    }


    public void buliddialog() {
        // 创建退出对话框
        isExit = new AlertDialog.Builder(this).create();
        // 设置对话框标题
        isExit.setTitle("系统提示");
        // 设置对话框消息
        isExit.setMessage("正在配置网关，退出可能造成配置错误");

        // 添加选择按钮并注册监听

        isExit.setButton("确定", listener);

        isExit.setButton2("取消", listener);
        // 显示对话框
        if (time != 100) {
            isExit.show();
        } else {
            YouXianActivity.this.finish();
        }
    }


    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event)

    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            buliddialog();
        return false;
    }

    /**
     * 监听对话框里面的button点击事件
     */
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()

    {

        public void onClick(DialogInterface dialog, int which)

        {

            switch (which)

            {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序

                    finish();

                    break;

                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

                    break;

                default:
                    break;

            }

        }

    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        m.time_value = 0;
        m.mac_user = null;
    }


    public void addwg() {
        add_time=1;
        SharedPreferences sp = getSharedPreferences("first", MODE_PRIVATE);
        String UserName = sp.getString("username", null);
        if (m.mac_user != null) {
            String mac = m.mac_user.toUpperCase();
            String name = mac.substring(8, 12);
            Integer it = Integer.parseInt(name, 16);
            it = it - 2;
            name = "智能网关" + Integer.toHexString(it);
            GateWay w = new GateWay();
            w.userId = m.userId;
            w.name = name;
            w.mac = mac;
            String j = JSON.toJSONString(w);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/add", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            flag2 = 4;
                            add_time=0;
                            HttpConnection.showToast(getBaseContext(),"网络异常");
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            if(arg0.result != null && !"".equals(arg0.result)){
                            arg0.result = AESUtil.decrypt(arg0.result);
                            GateWay p = JSON.parseObject(arg0.result, GateWay.class);
                            if (0 == p.status) {
                                GetDeviceList();
                            } else if (-5 == p.status) {
                                flag2 = 3;
                                add_time=0;
                                HttpConnection.showToast(getBaseContext(),p.msg);
                            } else if (-7 == p.status) {
                                flag2 = 4;
                                add_time=0;
                                HttpConnection.showToast(getBaseContext(),p.msg);

                            }

                        }else{
                                HttpConnection.showToast(getBaseContext(),"服务器错误");

                            }}
                    });
        } else {
            flag2 = 2;
        }
    }

    private void GetDeviceList() {
        GateWay Gw = new GateWay();
        Gw.userId = m.userId;
        Gw.status = 1;
        String j = JSON.toJSONString(Gw);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/getDeviceList", params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", YouXianActivity.this);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String status=jb.getString("status");
                            if("0".equals(status)){
                            JSONArray ja = jb.getJSONArray("deviceList");
                            m.m_gateway = (ArrayList<GateWay>) JSON.parseArray(ja.toString(), GateWay.class);
                            flag2 = 1;
                            add_time = 1;}else{
                                HttpConnection.toastLog("服务器错误", YouXianActivity.this);
                            }
                        } else {
                            HttpConnection.toastLog("服务器错误", YouXianActivity.this);

                        }
                    }

                });

    }


}







